package com.clipperl.jingfen

import android.annotation.TargetApi
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import android.os.SystemClock
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import okhttp3.*
import org.json.JSONException
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

/**
 * 后台任务 sevice
 */
class LongRunningService : Service() {

    var appkey = BuildConfig.APP_KEY
    var appsecret = BuildConfig.APP_SECRET
    var order_row_api = "jd.union.open.order.row.query"
    var timestamp = "2020-09-26 22:27:18"
    var startTime = "2020-09-29 16:00:00"
    var endTime = "2020-09-29 16:59:00"
    /**通知id*/
    var mNotifyId = 0
    /**刷新时间间隔 单位：ms*/
    val mRefreshInterval: Long = 10 * 60 * 1000

    var localBroadcastManager: LocalBroadcastManager? = null

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        localBroadcastManager = LocalBroadcastManager.getInstance(this)
        thread {
//            Log.d("jf", "executed at " + Date().toString())
            jdTask()
        }
        val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val triggerAtTime = SystemClock.elapsedRealtime() + mRefreshInterval
        val alarmIntent = Intent(this, AlarmReceiver::class.java)
        val pi = PendingIntent.getBroadcast(this, 0, alarmIntent, 0)
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi)
        return super.onStartCommand(intent, flags, startId)
    }

    fun jdTask() {
        // 记录当前时间
        val curTime = System.currentTimeMillis()
        val before10Time = System.currentTimeMillis() - mRefreshInterval
        startTime = getCurrTime(before10Time)
        endTime = getCurrTime(curTime)

        //获取当前的时间戳
        timestamp = getCurrTime(null)
        Log.d("jf", "timeStamp-->$timestamp")
        val signStr = getSignStr()
        val md5Str = getMd5Value(signStr)
//        Log.d("jf", "md5-->$md5Str")
        val url = initUrl(md5Str)
//        Log.d("jf", "url-->$url")
        okhttpGet(url)
    }


    /**
     * yyyy-M-d HH:mm:ss
     */
    private fun getCurrTime(time: Long?): String {
        val d = if (time == null) Date() else Date(time)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(d)
    }

    private fun initUrl(signStr: String): String {
        return "https://router.jd.com/api?" +
                "v=1.0" +
                "&method=" + order_row_api +
                "&access_token=" +
                "&app_key=" + appkey +
                "&sign_method=md5" +
                "&format=json" +
                "&timestamp=" + timestamp +
                "&sign=" + signStr +
                "&param_json={\"orderReq\":{\"startTime\":\"" + startTime + "\",\"pageSize\":\"10\",\"endTime\":\"" + endTime + "\",\"type\":\"1\",\"pageIndex\":\"0\"}}"
    }

    //    @Throws(IOException::class, JSONException::class)
    fun okhttpGet(url: String) {
        val client = OkHttpClient()
        val request: Request = Request.Builder().url(url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
//                Toast.makeText(this, "网络请求失败\n${e.message}", Toast.LENGTH_LONG).show()
                notifyMsg("异常", "网络请求失败\n${e.message}")
                sendMsgToUiThread("网络请求失败\n${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                try {
                    val responseStr = response.body?.string()
                    val jdBean: JdBean = GsonTool.fromJson(responseStr, JdBean::class.java)
                    if (jdBean.jd_union_open_order_row_query_response != null) {
                        val content = jdBean.jd_union_open_order_row_query_response.result
                        Log.d("jf", "内部数据为-->$content")
//                        tv_content.post { tv_content.text = "请求时间：${timestamp}，\n内部数据：${content}" }
                        sendMsgToUiThread("请求时间：${timestamp}，\n内部数据：${content}")
                        val jdInBean: JdInBean = GsonTool.fromJson(content, JdInBean::class.java)
                        val list = jdInBean.data
                        if (list != null && list.size > 0) {
                            notifyMsg("总价:${list[0].price}，佣金:${list[0].estimateFee}，下单时间:${list[0].orderTime}", list[0].skuName)
                        }
                    } else {
//                        tv_content.post { tv_content.text = responseStr }
                        responseStr?.let { sendMsgToUiThread(it) }
                    }
                } catch (e: Exception) {
//                    tv_content.post { tv_content.text = e.message }
                    e.message?.let { sendMsgToUiThread(it) }
                    notifyMsg("异常", "${e.message}")
                }
            }
        })
    }

    private fun sendMsgToUiThread(msg: String){
        var intent = Intent("send_msg")
        intent.putExtra("msg", msg)
        localBroadcastManager?.sendBroadcast(intent)
    }

    private fun getSignStr(): String {
        return appsecret.toString() + "app_key" + appkey + "formatjsonmethod" + order_row_api +
                "param_json{\"orderReq\":{\"startTime\":\"" + startTime + "\",\"pageSize\":\"10\",\"endTime\":\"" + endTime + "\",\"type\":\"1\",\"pageIndex\":\"0\"}}" +
                "sign_methodmd5timestamp" + timestamp + "v1.0" + appsecret
    }

    private fun getMd5Value(sSecret: String): String {
        try {
            val bmd5 = MessageDigest.getInstance("MD5")
            bmd5.update(sSecret.toByteArray())
            var i: Int
            val buf = StringBuffer()
            val b = bmd5.digest()
            for (offset in b.indices) {
                i = b[offset].toInt()
                if (i < 0) i += 256
                if (i < 16) buf.append("0")
                buf.append(Integer.toHexString(i))
            }
            return buf.toString().toUpperCase(Locale.ROOT)
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return "md5加密失败"
    }

    @Throws(IOException::class, JSONException::class)
    private fun okhttpDingGet(url: String) {
        val client = OkHttpClient()
        val request: Request = Request.Builder().url(url)
            .build()
        val response = client.newCall(request).execute()
        val responseStr = response.body?.string()
        Log.d("jf", "$response = responseStr")
    }

    fun notifyMsg(title: String, content: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            sendChatMsgAndroid8(title, content)
        } else {
            notifyMsgBefore8(title, content)
        }
    }

    fun notifyMsgBefore8(title: String, content: String) {
        val notification: Notification
        val intent = Intent(this, MainActivity::class.java)
        //点击通知栏消息跳转页
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

        //创建通知消息管理类
        val manager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder = NotificationCompat.Builder(this) //创建通知消息实例
            .setContentTitle(title)
            .setContentText(content)
            .setWhen(System.currentTimeMillis()) //通知栏显示时间
            .setSmallIcon(R.mipmap.ic_launcher_round) //通知栏小图标
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)) //通知栏下拉是图标
            .setContentIntent(pendingIntent) //关联点击通知栏跳转页面
            .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知消息优先级
            .setAutoCancel(true) //设置点击通知栏消息后，通知消息自动消失
            //                .setSound(Uri.fromFile(new File("/system/MP3/music.mp3"))) //通知栏消息提示音
            //                .setVibrate(new long[]{0, 1000, 1000, 1000}) //通知栏消息震动
            //                .setLights(Color.GREEN, 1000, 2000) //通知栏消息闪灯(亮一秒间隔两秒再亮)
            .setDefaults(NotificationCompat.DEFAULT_ALL) //通知栏提示音、震动、闪灯等都设置为默认

        notification = builder.build()
        //id为通知栏消息标识符，每个id都是不同的
        manager.notify(mNotifyId++, notification)
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance)
        val notificationManager = getSystemService(
            Context.NOTIFICATION_SERVICE
        ) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    fun sendChatMsgAndroid8(title: String, content: String) {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        //点击通知栏消息跳转页
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
        val notification = NotificationCompat.Builder(this, "notify")
            .setContentTitle(title)
            .setContentText(content)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_foreground))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()
        manager.notify(mNotifyId++, notification)
    }
}